import { baseUrl } from './url';

export interface RequestOptions<T, R> {
  url ?: string
  method ?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
  Logintoken ?: string
  showloading ?: boolean
  data ?: T
  success : (result : R) => void,
  fail ?: (code : number, message ?: string) => void
}
interface PsdArgs<T> {
  param : T
}
interface PsdArgs1<T> {
  param ?: T
}
export interface PsdResult<T> {
  code : number
  message ?: string
  content ?: T
}
interface PsdResult2<T> {
  code : number
  message ?: string
  data : T
}
function doRequest<T, R>(options : RequestOptions<T, R>) {
  if (options.showloading) { // 显示加载中 效果
    uni.showLoading({
      title: '',
      mask: true,
    });
  }
  uni.request({
    url: options.url,
    method: options.method ?? 'POST',
    dataType: 'json',
    timeout: 100000,
    header: { Logintoken: options.Logintoken },
    data: options?.data,
    success: (res) => {
      if (res.statusCode == 200) {
        const result = res.data as PsdResult<R>;
        if (result.code == 0 || result.code == 200 || result.code == 2000) {
          options.success(result.content);
        } else if (result.code == 101) {
          uni.showModal({ content: '无合同信息', showCancel: false });
        } else if (options.fail) {
          options.fail(result.code, result?.message);
        } else {
          uni.showModal({ content: `url:${options.url} \ncode: ${result.code}\n 错误： ${result?.message}` ?? '', showCancel: false });
          // uni.showModal({ content: `请联系管理员，发生系统错误!\n${result?.message}`, showCancel: false });
        }
      } else {
        uni.showModal({ content: `url:${options.url} \ncode: ${res.statusCode}\n 错误： ${res.errMsg}` ?? '', showCancel: false });
        options.fail(res.statusCode, '');
      }
    },
    fail: (err) => {
      // uni.showToast({ icon: "none", title: err?.errMsg ?? "未知错误" })
      options.fail(1, JSON.stringify(err));
    },
    // 完成之后关闭加载效果
    complete: () => {
      //  关闭正在等待的图标
      setTimeout(() => {
        uni.hideLoading();
      }, 1000);
    },
  });
}
export function request<T, R>(options : RequestOptions<T, R>) {
  const Logintoken = uni.getStorageSync('Logintoken');
  if (Logintoken === '') {
    doLogin({
      success: (Logintoken : string, phone : string) => {
        uni.setStorageSync('Logintoken', Logintoken);
        uni.setStorageSync('phone', phone);
        doRequest<T, R>(Object.assign(options, { Logintoken }));
        uni.closeAuthView();
      },
      // fail: options.fail,
      fail: (err) => {
        uni.closeAuthView();
        options.fail({ code: 1, message: JSON.stringify(err) });
      },
    });
    return;
  }
  doRequest<T, R>(
    {
      ...options,
      Logintoken,
      fail: (code : number, message : string) => {
        if (code == 4000) {
          uni.removeStorageSync('Logintoken');
          uni.removeStorageSync('phone');
          doLogin({
            success: (Logintoken : string, phone : string) => {
              uni.setStorageSync('Logintoken', Logintoken);
              uni.setStorageSync('phone', phone);
              doRequest<T, R>(Object.assign(options, { Logintoken }));
              uni.closeAuthView();
            },
            // fail: options.fail
            fail: (err) => {
              uni.closeAuthView();
              options.fail(1, JSON.stringify(err));
              uni.showModal({ content: `code: ${code}\n 错误： ${message}` ?? '', showCancel: false });
            },
          });
        } else if (options.fail) {
          options.fail(code, message);
        } else {
          uni.showModal({ content: `请联系管理员，发生系统错误!\n${code}\n${message}` ?? '', showCancel: false });
        }
      },
    }
  );
}
// 返回类型
// {
// 	code: '',
// 	content: {
// 		code: '',
// 		data: T
// 	}
// }

export function request2<T, R>(options : RequestOptions<T, R>) {
  request<PsdArgs<T>, PsdResult2<R>>(
    {
      ...options,
      data: { param: options?.data },
      success: (res : PsdResult2<R>) => {
        if (res.code == 0 || res.code == 200 || res.code == 2000) {
          options.success(res.data);
        } else if (options.fail) {
          options.fail(res.code, res?.message);
        } else {
          uni.showModal({ content: res?.message ?? '未知错误', showCancel: false });
        }
      },
    }
  );
}
// 返回类型
// {
// 	code: '',
// 	content: T
// }
interface PsdResult3<T> {
  status ?: number
  message ?: string
  data ?: T
}
export function request3<T, R>(options : RequestOptions<T, R>) {
  request<PsdArgs<T>, PsdResult2<R>>(
    {
      ...options,
      data: { param: options?.data },
      success: (res : PsdResult3<R>) => {
        if (res.status) {
          uni.showModal({ content: res?.message ?? '未知错误', showCancel: false });
          options.fail(res.status, res?.message);
        } else {
          options.success(res);
        }
      },
    }
  );
}
interface PsdResult31<T> {
  status ?: number
  message ?: string
  data ?: T
  pagination ?: Object
}
export function request31<T, R>(options : RequestOptions<T, R>) {
  request<PsdArgs1<T>, PsdResult2<R>>(
    {
      ...options,
      success: (res : PsdResult31<R>) => {
        if (res.status) {
          uni.showModal({ content: res?.message ?? '未知错误', showCancel: false });
          options.fail(res.status, res?.message);
        } else {
          options.success(res);
        }
      },
    }
  );
}
// 返回类型
// {
// 	code: '',
// 	content: {
// 		code: '',
// 		data: T
// 	}
// }
interface PsdResult4<T> {
  status : number
  message ?: string
  data : T
}
export function request4<T, R>(options : RequestOptions<T, R>) {
  request<PsdArgs<T>, PsdResult4<R>>(
    {
      ...options,
      data: { param: options?.data },
      success: (res : PsdResult4<R>) => {
        if (res.status == 0 || res.status == 200 || res.status == 2000) {
          options.success(res.data);
        } else if (options.fail) {
          options.fail(res.status, res?.message);
        } else {
          uni.showModal({ content: res?.message ?? '未知错误', showCancel: false });
        }
      },
    }
  );
}
// 返回类型 请求参数不加 param 也不需要登录
// {
// 	code: '',
// 	content: {
// 		code: '',
// 		data: T
// 	}
// }

export function request5<T, R>(options : RequestOptions<T, R>) {
  doRequest<PsdArgs1<T>, PsdResult4<R>>(
    {
      ...options,
      success: (res : PsdResult4<R>) => {
        if (res.status == 0 || res.status == 200 || res.status == 2000) {
          options.success(res.data);
        } else if (options.fail) {
          options.fail(res.status, res?.message);
        } else {
          uni.showModal({ content: res?.message ?? '未知错误', showCancel: false });
        }
      },
    }
  );
}
function preLogin(options : { redo : number, success : () => void, fail : (code : number, message : string) => void }) {
  uni.preLogin({
    provider: 'univerify',
    success: options.success,
    fail: (res) => {
      // 失败
      console.log('preLogin fail res: ', res);
      if (options?.redo > 3) {
        options.fail(1, JSON.stringify(res));
      } else {
        options.redo += 1;
        preLogin(options);
      }
    },
  });
}
interface LoginResult {
  data : {
    token : string
    phone : string
  }
}
function GetTokenByPhone(options : { data : AuthResult, success : (result : LoginResult) => void, fail : (err : PsdResult<LoginResult>) => void }) {
  console.log(baseUrl)
  uni.request({
    method: 'POST',
    url: `${baseUrl}/bspsd/v2/asi/GetTokenByPhone`,
    dataType: 'json',
    data: { param: options.data },
    success: (res) => {
      const result : PsdResult<LoginResult> = res.data as PsdResult<LoginResult>;
      if (result.code == 0 || result.code == 200) {
        options.success(result.content);
      } else {
        options.fail(result);
      }
    },
    fail: (err) => {
      console.log(err);
      options.fail({ code: 1, message: JSON.stringify(err) });
    },
  });
}
interface AuthResult {
  openid ?: string
  access_token ?: string
}
export function doLogin(options : { success : (Logintoken : string, phone : string) => void, fail : (code : number, message ?: string) => void }) {
  const success = function (res) {
    console.log(res.authResult); // {openid:'登录授权唯一标识',access_token:'接口返回的 token'}
    if (res.authResult as AuthResult) {
      const authResult = res.authResult as AuthResult;
      GetTokenByPhone({
        data: { openid: authResult.openid, access_token: authResult.access_token },
        success: (res1) => {
			 console.log('Logintoken', res1.data.token);
			 console.log('phone', res1.data.phone);
          uni.setStorageSync('Logintoken', res1.data.token);
          uni.setStorageSync('phone', res1.data.phone);
          options.success(res1.data.token, res1.data.phone);
        },
        fail: options.fail,
      });
    } else {
      options.fail(1, '手机一键登录运营商返回数据结构未知！');
    }
  };
  preLogin({
    redo: 0,
    success: () => {
      uni.login({
        provider: 'univerify',
        univerifyStyle: {
          fullScreen: true, // 是否全屏显示，true表示全屏模式，false表示非全屏模式，默认值为false。
          backgroundColor: '#ffffff', // 授权页面背景颜色，默认值：#ffffff
          phoneNum: {
            color: '#000000', // 手机号文字颜色 默认值：#000000
          },
          slogan: {
            color: '#8a8b90', //  slogan 字体颜色 默认值：#8a8b90
          },
          icon: {
            path: 'static/img/logoicon.png', // 自定义显示在授权框中的logo，仅支持本地图片 默认显示App logo
          },
          authButton: {
            normalColor: '#3479f5', // 授权按钮正常状态背景颜色 默认值：#3479f5
            highlightColor: '#2861c5', // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
            disabledColor: '#73aaf5', // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）
            textColor: '#ffffff', // 授权按钮文字颜色 默认值：#ffffff
            title: '本机号码一键登录', // 授权按钮文案 默认值：“本机号码一键登录”
          },
          otherLoginButton: {
            visible: false, // 是否显示其他登录按钮，默认值：true
          },
        },
        success,
        fail: options.fail,
        // complete() {
        // 	uni.closeAuthView()
        // }
      });
    },
    fail: options.fail,
  });
}